﻿var http = require('http');
var fs = require('fs');

var url = "http://tu.duowan.com/index.php?r=show/getByGallery/&gid=137273&_=1531830598687"
         

startRequest(url);

function startRequest(x) {
  //采用http模块向服务器发起一次get请求      
  http.get(x, function (res) {
    //用来存储请求网页的整个html内容
    var html = '';
    //防止中文乱码  
    res.setEncoding('utf-8'); 
    // 监听data事件，每次取一块数据
    res.on('data', function (chunk) {
      html += chunk;
    });
    //监听end事件，如果整个网页内容的html都获取完毕，就执行回调函数
    res.on('end', function () {
      var data = JSON.parse(html.toString());
      for (var i = 0; i < data.picInfo.length; i++) {
        var lastadress = data.picInfo[i].url.split('.')[3];
        var filename = data.picInfo[i].add_intro + '.'+ lastadress;
        var imgurl = data.picInfo[i].url;

        savedContent(imgurl, filename);
      }
    });

  }).on('error', function (err) {
    console.log(err);
  });
}
//在本地存储所爬取内容
function savedContent(imgurl, filename) {
  var streaml = fs.createWriteStream('./imgs/' + filename);
  http.get(imgurl, function (res) {
    res.pipe(streaml);
    console.log(filename + '读取完毕');
  })
}